import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' show DataCell, DataColumn;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../../components/buttons.dart';
import '../../components/data_table.dart';
import '../../model/test_batch_model.dart';
import '../../route/router.dart';
import '../../utils/date_utils.dart';
import '../app/app_dict_data.dart';
import 'test_batch_view_model.dart';

/// 考试批次:视图列表
class TestBatchViewList extends StatefulWidget {
  const TestBatchViewList({super.key});

  @override
  State<TestBatchViewList> createState() => _TestBatchViewListState();
}

class _TestBatchViewListState extends State<TestBatchViewList> {
  final queryFormKey = GlobalKey<FormState>();
  final tableKey = GlobalKey<DataTableState<TestBatchItemRes>>();

  @override
  void initState() {
    super.initState();
    //加载数据
    final model = context.read<TestBatchViewModel>();
    model.loadInit(afterHandler: () => query(model));
  }

  void query(final TestBatchViewModel model) => model.query();

  Widget buildQueryForm(final TestBatchViewModel model) {
    Widget buildField(TestBatchQueryField field,
        Widget Function(TextEditingController? c, String label) handler) {
      final label = field.label;
      final controller = model.getController(field);
      final child = handler.call(controller, label);
      return SizedBox(
        width: 128.w,
        child: InfoLabel(
          label: label,
          child: child,
        ),
      );
    }

    return Form(
      key: queryFormKey,
      child: Wrap(
        spacing: 5.w,
        children: [
          //学年学期
          buildField(
            TestBatchQueryField.semester,
            (c, label) => TextFormBox(controller: c, placeholder: label),
          ),
          //年级
          buildField(
            TestBatchQueryField.grade,
            (c, label) => TextFormBox(controller: c, placeholder: label),
          ),
          //考试层次
          buildField(
            TestBatchQueryField.level,
            (c, label) => TextFormBox(controller: c, placeholder: label),
          ),
          //名称
          buildField(
            TestBatchQueryField.name,
            (c, label) => TextFormBox(controller: c, placeholder: label),
          ),
          //状态
          buildField(
            TestBatchQueryField.status,
            (ctr, label) => ComboboxFormField(
              placeholder: Text(label),
              items: model.statusOpts,
              onChanged: (val) => ctr?.text = val ?? '',
            ),
          ),
        ],
      ),
    );
  }

  Widget buildQueryBars(final TestBatchViewModel model) => Wrap(
        spacing: 2.w,
        children: [
          //查询
          buttons.query(onPressed: () => query(model)),
          //重置
          buttons.reset(onPressed: () {
            queryFormKey.currentState?.reset();
            model.cleanQueryFields();
            query(model);
          }),
          //新增
          buttons.add(onPressed: () => editHandler(model, null)),
        ],
      );

  void editHandler(TestBatchViewModel model, final String? id) async {
    final ret = await context.pushNamed<bool>(
      getRoteName(AppRote.testBatchEdit),
      queryParameters: {'id': id ?? ''},
    );
    if (ret ?? false) {
      //查询数据
      query(model);
    }
  }

  @override
  Widget build(final BuildContext context) => Consumer<TestBatchViewModel>(
        builder: (context, model, _) => ScaffoldPage.scrollable(
          header: Column(children: [
            PageHeader(title: Text(getRoteTitle(AppRote.testLevel))),
            Padding(
              padding: () {
                final padding = PageHeader.horizontalPadding(context);
                return EdgeInsetsDirectional.symmetric(horizontal: padding);
              }(),
              child: Row(
                children: [
                  //查询条件
                  buildQueryForm(model),
                  //占位
                  Expanded(child: Container()),
                  //查询按钮
                  buildQueryBars(model),
                ],
              ),
            ),
            SizedBox(height: 15.h),
          ]),
          children: [
            //数据列表
            buildTable(model),
          ],
        ),
      );

  Widget buildTable(final TestBatchViewModel model) {
    final labels = <String>['名称', '学年学期', '年级', '层次', '状态', '创建时间', '操作'];
    DataCell buildCell(String? Function() handler) => DataCell(Text(
          handler.call() ?? '',
          softWrap: false,
          overflow: TextOverflow.ellipsis,
        ));
    final String dtFormat = 'yyyy-MM-dd HH:mm:ss';
    return DataTable<TestBatchItemRes>(
      key: tableKey,
      model: model.queryModel,
      columns: labels.map((label) => DataColumn(label: Text(label))).toList(),
      onLoadData: () => query(model),
      onRowCallback: (row) => [
        //名称
        buildCell(() => row.name),
        //学年学期
        buildCell(() => row.semesterId),
        //年级
        buildCell(() => '${row.gradeVal}'),
        //层次
        buildCell(() => row.levelId),
        //状态
        buildCell(() => appDictData.getLabel('status', row.status)),
        //创建时间
        buildCell(() => dateUtils.format(dtFormat, row.createdAt)),
        //操作
        DataCell(OverflowBar(
          spacing: 2.w,
          children: [
            //修改
            buttons.modify(onPressed: () {
              final id = row.id;
              if (id.isNotEmpty) {
                editHandler(model, id);
              }
            }),
            //删除
            buttons.delete(onPressed: () {
              final id = row.id;
              if (id.isNotEmpty) {
                model.onDeleteHandler(id);
              }
            }),
          ],
        )),
      ],
    );
  }
}
